package handler

import (
	"encoding/json"
	amodel "funlog-gserver/model/api"
	model "funlog-gserver/model/db"
	nsqModel "funlog-gserver/model/nsq"
	"funlog-gserver/stored/db"
	nsq "funlog-gserver/stored/nsq"
	redis "funlog-gserver/stored/redis"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

//LogIndex  日志上报接口
func LogIndex(c *gin.Context) {
	var logJson amodel.LogInfo
	err := c.ShouldBindJSON(&logJson)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	if logJson.AuthInfo.Apikey == "" {
		SendResponse(c, QUERY_PARAMS_ERROR, "APIKEY不能为空", nil)
		return
	}
	app := model.Application{}
	val, _ := redis.RDB.Get("app_apikey_" + logJson.AuthInfo.Apikey).Result()
	//如果查不到那么就去数据库查
	if val == "" {
		result := db.DB.Where("appkey = ? and status =1", logJson.AuthInfo.Apikey).First(&app)
		//如果找不到这个应用
		if result.Error != nil {
			SendResponse(c, DB_QUERY_ERROR, "应用不存在", nil)
			return
		}
		b, err := json.Marshal(app)
		if err != nil {
			SendResponse(c, SYATEM_ERROR, "系统错误", nil)
			return
		}
		err = redis.RDB.Set("app_apikey_"+logJson.AuthInfo.Apikey, string(b), time.Second*10).Err()
		if err != nil {
			SendResponse(c, RDB_INSER_ERROR, "系统错误", nil)
			return
		}

	} else {
		//转回来
		if err = json.Unmarshal([]byte(val), &app); err != nil {
			SendResponse(c, SYATEM_ERROR, "系统错误", nil)
			return
		}
	}

	var nsqMsg *nsqModel.NMessage
	//如果等于日志
	if topic, ok := nsqModel.NMessageTypeMap[logJson.Data.Type]; ok {
		logJson.AuthInfo.IPAddr = c.ClientIP()
		logJson.Data.ReportTime = time.Now()
		nsqMsg = &nsqModel.NMessage{Topic: topic, Body: logJson}
	} else {
		SendResponse(c, QUERY_PARAMS_ERROR, "上报类型错误", nil)
		return
	}
	//如果是认识的
	if nsqMsg != nil {
		//推送处理
		err = nsq.PublishMsg(nsqMsg)
		if err != nil {
			SendResponse(c, SYATEM_ERROR, "系统错误", nil)
			return
		}
	} else {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	}
	//如果日志插进去了就不返回任何信息
	c.Status(http.StatusOK)
}
